<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/14
 * Time: 15:22
 */

namespace app\admin\controller;


use think\Db;
use think\Request;
use app\admin\model\UUser as UUserModel;//用户
use app\admin\model\Mechanism as MechanismModel;//机构

class Uuser extends Base
{
    /**
     * 普通用户列表展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $where = [];
            if(isset($params['key']) && $params['key'] != ''){
                $where['uuu.user_username|uuu.user_phone'] = ['like', "%" . $params['key'] . "%"];
            }
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field = 'uuu.is_zyx,uuu.user_id, uuu.user_phone, uuu.user_username, uuu.user_attestation, uuu.user_me_content, 
            uuu.user_number, uuu.last_login_time, uuu.user_status, uuu.user_to_mechanism_id, um.mechanism_name';
            $uUserModel = new UUserModel();
            $lists = $uUserModel->getUserLists($field, $where, $page, $limits);
            $count = $uUserModel->countNum($where);
            foreach($lists as $key=>&$list){
                //最后登录时间
                if(!empty($list['last_login_time'])){
                    $list['last_login_time'] = date('Y-m-d H:i', $list['last_login_time']);
                }else{
                    $list['last_login_time'] = '';
                }
                //志愿者编码
                if(empty($list['user_number'])){
                    $list['user_number'] = '未加入机构';
                }else{
                    $list['user_number'] = trim($list['user_number'], ',');
                }
                //机构
                if($list['user_to_mechanism_id'] == -1){
                    $list['mechanism_name'] = '未加入机构';
                }
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        if(session('?uuuu_user_id')){
            session('uuuu_user_id',null);
        }
        return $this->fetch("uuser/index");
    }
    
    /**
     * 添加用户
     * @return mixed|\think\response\Json
     */
    public function uUserAdd(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $uUserModel = new UUserModel();
            $mechanismModel = new MechanismModel();
            $phone = Db::table('up_u_user')->where('user_phone', $params['user_phone'])->find();
            if($phone){
                return json(['code' => 100, 'data' => '', 'msg' => '该手机号已被注册']);
            }
            if($params['user_attestation'] == 1){//未认证，则mechanism_id为-1，无志愿者编号
                $params['mechanism_id'] = -1;
                $num = '';
            }elseif($params['user_attestation'] == 2){//认证中，无志愿者编号
                $num = '';
            }else{//已认证，这需要志愿者编号
                $num = $uUserModel->getMaxNum($params['mechanism_id']);
                $res = $mechanismModel->getMechanismCode($params['mechanism_id']);
                $mechanism_code = trim($res['mechanism_code'], ',');
                if(!$num){//该机构暂无志愿者
                    $num = ',' . $mechanism_code . '00001' . ',';
                }else{
                    $num = trim($num, ',') + 1;
                    $leng = strlen($num);
                    $totalLeng = '';
                    if($res['mechanism_type'] == 1){
                        $totalLeng = 8;
                    }elseif($res['mechanism_type'] == 2){
                        $totalLeng = 11;
                    }elseif($res['mechanism_type'] == 3){
                        $totalLeng = 14;
                    }elseif($res['mechanism_type'] == 4){
                        $totalLeng = 17;
                    }elseif($res['mechanism_type'] == 5){
                        $totalLeng = 20;
                    }
                    $zero = '';
                    if($leng < $totalLeng){
                        for($i=$leng; $i<$totalLeng; $i++){
                            $zero .= '0';
                        }
                    }
                    $num = ',' . $zero . $num . ',';
                }
            }
            //志愿者编号
            $data = [
                'user_username' => $params['user_username'],
                'user_phone' => $params['user_phone'],
                'user_password' => md5($params['user_password']),
                'user_attestation' => $params['user_attestation'],
                'user_to_mechanism_id' => $params['mechanism_id'],
                'user_number' => $num,
                'user_time' => date('Y-m-d H:i:s'),//注册时间
                'user_join_time' => date('Y-m-d H:i:s'),//提交资料时间
            ];
            $res = $uUserModel->insertUser($data);
            if($res){
                return json(['code' => 200, 'data' => '', 'msg' => '注册成功']);
            }else{
                return json(['code' => 100, 'data' => '', 'msg' => '注册失败']);
            }
        }
        $mechanismModel = new MechanismModel();
        $mechanismInfo = $mechanismModel->getMechanismInfo();
        $mechanismInfo = getCate($mechanismInfo);
        $this->assign('mechanismInfo', $mechanismInfo);
        return $this->fetch('uuser/uuseradd');
    }
    
    /**
     * 修改志愿者编号
     * 可选择的机构为无下级机构、无机构志愿者、已认证、除总队以外的机构
     * @return mixed|\think\response\Json
     */
    public function editUserCode(){
        $uUserModel = new UUserModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $params['mechanism_id'] = explode('&', $params['mechanism_id']);
            $new_code = ',' . $params['mechanism_id'][1] . $params['new_code'] . ',';
            $data = [
                'user_to_mechanism_id' =>$params['mechanism_id'][0],
                'user_number' => $new_code
            ];
            $res = $uUserModel->updateCode($params['id'], $data);
            if($res){
                return json(['code' => 200, 'data' => '', 'msg' => '修改成功']);
            }else{
                return json(['code' => 100, 'data' => '', 'msg' => '修改失败']);
            }
        }
        $id = input('id');
        $mechanismModel = new MechanismModel();
        $lists = $mechanismModel->getNoSonMechanism();//获取所有无下级机构的机构
        foreach($lists as $key=>&$list){
            $res = Db::table('up_u_user')->where('user_to_mechanism_id', $list['mechanism_id'])->count();
            if($res != 0){//去掉有机构志愿者的机构
                unset($lists[$key]);
            }
            $list['mechanism_code'] = trim($list['mechanism_code'], ',');
        }
        $code = $uUserModel->getUserCode($id);
        $code = trim($code, ',');
        $this->assign([
            'lists' => $lists,
            'code' => $code,
            'id' => $id
        ]);
        return $this->fetch('uuser/editusercode');
    }
    
    /**
     * 认证详情
     * @return mixed
     */
    public function uUserAttestation(){
        $user_id = input('param.id');
        $field = 'uuu.user_rel_name, uuu.user_card, um.mechanism_name, ua.district, ua1.assortment_name as user_hospital, 
        ua2.assortment_name as user_department, ua3.assortment_name as user_title, ua4.assortment_name as user_post, 
        uuu.user_business_image, uuu.user_attestation, uuu.user_false_reason';
        $uUserModel = new UUserModel();
        $info = $uUserModel->getAttestation($user_id, $field);
        $info['user_business_image'] = explode(',', trim($info['user_business_image'], ','));
        $this->assign('info', $info);
        return $this->fetch('uuser/uuserattestation');
    }
    
    /**
     * 停用/启用用户
     * @return \think\response\Json
     */
    public function uUserStatus(){
        $params = input('param.');
        $uUserModel = new UUserModel();
        $res = $uUserModel->uUserStatus($params['num'], $params['id']);
        return json(['code' => $res['code'], 'data' => $res['data'], 'msg' => $res['msg']]);
    }
    
    /**
     * checkPhone 验证手机号的合法性
     */
    public function checkPhone(){
        $params = input('param.');
        if(!preg_match("/^1[345678]{1}\d{9}$/",$params['mechanism_member_phone'])){
            echo "false";
        }else{
            echo "true";
        }
    }

    /**
     * 添加
     */
    public function volunteer(){
        if(request()->isAjax()){
            $ids = input('param.id');
            $data['content'] = input('param.content');
            $data['user_id'] = $ids;
            $data['create_time'] = date('Y-m-d H:i:s',time());
            Db::startTrans();// 启动事务

            $volunteer_id = Db::table('up_volunteer')->insertGetId($data);
            $aa = Db::table('up_volunteer')->where('volunteer_id',$volunteer_id)->setField('volunteer_sort',$volunteer_id);
            $bb = Db::table('up_u_user')->where('user_id',$ids)->setField('is_zyx',2);

            if($volunteer_id&&$aa&&$bb){
                Db::commit();// 提交事务
                writelog(session('uid'),session('username'),'设置志愿者之星成功',1);
                return ['code' => 200,'data' => '', 'msg' => '设置志愿者之星成功'];
            }else{
                Db::rollback ();//回滚事务
                writelog(session('uid'),session('username'),'设置志愿者之星失败',2);
                return ['code' => 100, 'data' => '', 'msg' => '设置志愿者之星失败'];
            }

        }
        $id = input('param.id');
        $where1['a.user_id'] = $id;
        $list = Db::table('up_u_user')->alias('a')
            ->join('up_mechanism um','um.mechanism_id = a.user_to_mechanism_id','left')
            ->join('up_assortment ua','ua.assortment_id = a.user_title','left')
            ->where($where1)
            ->field('a.user_id,a.user_username,a.user_rel_name,a.user_phone,a.user_card,
            ua.assortment_name,um.mechanism_name
            ')
            ->find();
            $total_time = '';
            $bir = substr($list['user_card'], 6, 8);
            $year = (int) substr($bir, 0, 4);
            $month = (int) substr($bir, 4, 2);
            $day = (int) substr($bir, 6, 2);
            $list['birthday'] = $year . "-" . $month . "-" . $day;
            $where['sign_time'] =array('>',0);
            $where['sign_end_time'] =array('>',0);
            $where['user_id'] =$list['user_id'];

            $count = Db::table('up_institutional_activities_member')->where($where)->select();
             $list['num'] = count($count);
            foreach ($count as $kk=>$vv){
                //查询这个活动举办时长
                $activity_time = Db::table('up_institutional_activities')->where('id',$vv['institutional_activities_id'])->value('activity_time');
                $time = strtotime($vv['sign_end_time']) - strtotime($vv['sign_time']);
                if(floor($time/3600) > $activity_time){//如果签到的时长大于活动的举办时长
                    $total_time += $activity_time;
                }else{
                    $total_time += floor($time/3600);
                }
            }
        $list['time'] = $total_time?$total_time:0;
        $this->assign('list',$list);
        return $this->fetch();
    }

    /***
     * 我的证书
     */
    public function certificate(){
        if(request()->isAjax()){
            extract(input());
            $map =array();
            $map['a.user_id'] = input('param.id');
            $page = input('page') ? input('page'):1;
            $limit = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::table('up_institutional_activities_member')
                ->alias ('a')
                ->join('up_institutional_activities uia','uia.id = a.institutional_activities_id')
                ->join('up_mechanism um','um.mechanism_id = uia.activity_mechanism_id','left')
                ->join('up_u_user uuu','uuu.user_id=a.user_id','left')
                ->where($map)
                ->count();//计算总页面
            $list = Db::table('up_institutional_activities_member')
                ->alias ('a')
                ->join('up_institutional_activities uia','uia.id = a.institutional_activities_id')
                ->join('up_mechanism um','um.mechanism_id = uia.activity_mechanism_id','left')
                ->join('up_u_user uuu','uuu.user_id = a.user_id','left')
                ->field('a.*,um.mechanism_name,uia.activity_name,uuu.user_username,uuu.user_rel_name,uuu.user_phone')
                ->page($page, $limit)
                ->where($map)
                ->select();//计算总页面

            foreach ($list as $key=>&$vo){
                if(strtotime($vo['sign_end_time'])>0){
                    $activity_time = Db::table('up_institutional_activities')->where('id',$vo['institutional_activities_id'])->value('activity_time');
                    $time = strtotime($vo['sign_end_time']) - strtotime($vo['sign_time']);
                    if(floor($time/3600) > $activity_time){//如果签到的时长大于活动的举办时长
                        $total_time = $activity_time;
                    }else{
                        $total_time = floor($time/3600);
                    }
                    $vo['total_time'] = $total_time;
                }else{
                    $vo['total_time'] = 0;
                }
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$list]);
        }
        if(!session('?uuuu_user_id')){
            session('uuuu_user_id',input('id'));
        }
        return $this->fetch();
    }

    /**
     * 编辑活动报名的签退时间
     */
    public function sign()
    {
        if(request()->isAjax()){
            $id = input('param.id');
            $data['sign_end_time'] = input('param.endTime');
            $res = Db::table('up_institutional_activities_member')->where('id',$id)->update($data);
            if($res){
                return json(['code' => 200, 'data' =>"", 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'data' => '', 'msg' => '编辑失败']);
            }
        }
        $id = input('param.id');
        $sign_end_time = Db::table('up_institutional_activities_member')->where('id',$id)->value('sign_end_time');
        $this->assign('id',$id);
        $this->assign('sign_end_time',$sign_end_time);
        return $this->fetch();
    }

    /**
     * 我的证书
     */
    public function diploma(){
        $id  = input('param.id');
        //查询自己参加的哪些活动
        //查询用户基本信息
        $user_info = Db::table('up_u_user')->alias('a')

            ->join('up_mechanism um','um.mechanism_id=a.user_to_mechanism_id','left')
            ->field('a.user_rel_name,um.mechanism_name,a.user_number,a.user_sh_time')
            ->where('a.user_id',$id)
            ->find();
        //获得的荣誉
        $where['sign_time'] =array('>',0);
        $where['sign_end_time'] =array('>',0);
        //参加的活动
        $activities_member = Db::table('up_institutional_activities_member')
            ->alias('a')
            ->join('up_institutional_activities uia','uia.id = a.institutional_activities_id')
            ->where($where)
            ->field('uia.activity_time,a.*')
            ->select();
        $total_time = '';
        foreach ($activities_member as $key=>$vo){
            if(strtotime($vo['sign_end_time'])>0){
                $time = strtotime($vo['sign_end_time']) - strtotime($vo['sign_time']);
                if(floor($time/3600) > $vo['activity_time']){//如果签到的时长大于活动的举办时长
                    $total_time += $vo['activity_time'];
                }else{
                    $total_time += floor($time/3600);
                }
            }
        }
        $mechanism_name = Db::table('up_mechanism')->where('mechanism_id',1)->value('mechanism_name');
        $user_info['num'] = count($activities_member);;//参加活动的次数
        $user_info['time'] = $total_time?$total_time:0;//参加活动的时间
        $user_info['mechanism_name_qf'] = $mechanism_name;//签发机构
        $user_info['user_number'] = trim($user_info['user_number'],',');
        $this->assign('user_info',$user_info);
        return $this->fetch();
    }
}